#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
# define SERV_PORT 9527

//单进程服务器
void sys_err(const char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int lfd = 0, cfd = 0; //lfd接收socket创建的文件描述符,cfd接受accept创建的与客户端通信的文件描述符
	int fret,i;//接受read返回，read函数返回读到的字节数
	char buf[4096], clit_ip[1024];

	struct sockaddr_in serv_addr, clit_addr;
	socklen_t clit_addr_len;

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);//本地字节序转网络字节序
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);//任意可用ip地址

	lfd = socket(AF_INET,SOCK_STREAM,0);
	if(lfd == -1){
		sys_err("server socket create error");
	}

	int ret = bind(lfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
	if(ret == -1){
		sys_err("server bind error");
	}

	ret = listen(lfd,128);
	if(ret == -1){
		sys_err("server listen error");
	}

	clit_addr_len = sizeof(clit_addr);
	cfd = accept(lfd,(struct sockaddr *)&clit_addr, &clit_addr_len);
	if(cfd == -1){
		sys_err("serveraccept error");
	}
	printf("client ip:%s, port:%d\n", 
		inet_ntop(AF_INET, &clit_addr.sin_addr.s_addr, clit_ip, sizeof(clit_ip)),
		ntohs(clit_addr.sin_port));

	//服务器建立完连接了，可以读数据了
	while(1){
		fret = read(cfd,buf,sizeof(buf));
		write(STDOUT_FILENO, buf ,fret);
		printf("\n");

		for(i=0; i<fret; i++){
			buf[i] = toupper(buf[i]);//对数据进行操作
		}

		write(cfd, buf,fret);
	}

	close(lfd);//关闭连接
	close(cfd);

	return 0;
}

